var fs = require("fs");
var _ = require("lodash");

let fileNameB = "../extra";
let fileNameC = "./data/weapon";
let outputFileName = "./lua/weapon.lua";

let extraData = JSON.parse(fs.readFileSync(`${fileNameB}.json`).toString()).weapon;
let mainData = JSON.parse(fs.readFileSync(`${fileNameC}.json`).toString());

let extraMap = new Map();
_.forEach(extraData, (e) => {
    let id = e.id;
    let data = {
        add_date: e.add_date,
    };
    extraMap.set(id, data);
});

let output = `local p = {}
`

_.forEach(mainData, (e) => {
    let data = e.data;
    let i = 0;
    let c = 0;
    let curHp = data.weaponMinHp;
    let curAtk = data.weaponMinAtk;
    let lastWeapon = undefined;
    let minLv = undefined;
    let curLv = 1;
    _.forEach(data.display, (x) => {
        let minHp = curHp;
        let minAtk = curAtk;

        let exData = extraMap.has(x.id) ? extraMap.get(x.id) : {};
        c++;
        for(;i < data.weaponStageConfig.length; i++) {
            let stage = data.weaponStageConfig[i];
            if (stage.class == c) {
                if (stage.weaponStageLevelLimt){
                    curAtk += (stage.addAtk || data.weaponAddAtk) * (stage.weaponStageLevelLimt - curLv)
                    curHp += (stage.addHp || data.weaponAddHp) * (stage.weaponStageLevelLimt - curLv)
                    curLv = stage.weaponStageLevelLimt;
                }
            } else break;
        }
        let str = `p['${x.id}'] = {
            ['name'] = '${x.name}',
            ['minAtk'] = '${minAtk}',
            ['minHp'] = '${minHp}',
            ['maxAtk'] = '${curAtk}',
            ['maxHp'] = '${curHp}',
            ['description'] = '${x.cnDescription}',
            ['length'] = '${x.length}',
            ['type'] = '${x.type}',
            ['weight'] = '${x.weight}',
            ['age'] = '${x.age}',
            ['lastWeapon'] = '${lastWeapon || ''}',
            ['minLv'] = '${minLv || ''}',
            ['weaponType'] = '${data.weaponType}',
            ['addDate'] = ${exData.add_date || "''"},
}
`;
        output += str;
        lastWeapon = x.id;
        minLv = curLv;
        curAtk += data.weaponAddAtk * (data.weaponMaxLevel - curLv)
        curHp += data.weaponAddHp * (data.weaponMaxLevel - curLv)
    })
});
output += `return p`

fs.writeFileSync(outputFileName, output);